import { constantRoutes } from '@/router'
import router, { resetRouter } from '@/router'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  auth: undefined,
  menu: undefined,
  menuAll: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = constantRoutes.concat(routes)
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUS: (state, data) => {
    state.menu = data
  },
  SET_MENUAll: (state, data) => {
    state.menuAll = data
  }
}

const actions = {
  generateRoutes({ commit }, route) {
    return new Promise(resolve => {
      let accessedRoutes = []; let menus = []
      accessedRoutes = addComponent(copyTree(route))
      menus = addMenus(copyTree(route))
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_MENUS', menus)
      commit('SET_MENUAll', menus)
      resetRouter()
      resolve(constantRoutes.concat(accessedRoutes))
    })
  },
  /**
   * 创建路由
   * @param commit
   * @param route
   */
  createRouter({ commit }, route) {
    const newRouter = JSON.parse(JSON.stringify(route))
    console.log(newRouter)
    const views = addComponent(newRouter)
    console.log(views)
    commit('SET_ROUTES', views)
    resetRouter()
    views.push({ path: '*', redirect: '/404' })
    router.addRoutes(views)
  }
}

/**
 * 生成路由
 * @param routes
 * @returns {*}
 */
function addComponent(routes, code) {
  const newRoutes = routes.concat()
  newRoutes.forEach((item, index) => {
    delete item.parentId
    delete item.menuCode
    item.ascription = code || item.ascription
    item.meta = {
      icon: item.icon,
      title: item.title,
      noCache: item.keepAlive,
      ascription: code || item.ascription
    }
    if (item.linkType === 1) {
      routes.splice(index, 1)
    } else {
      if (item.component && item.component === 'Layout') {
        item.component = Layout
      } else {
        // console.log(view(item.component))
        const url = item.component
        // item.component = view(url)
        // item.component = () => import(`@/views/${url}`)
        item.component = reslove => {
          require(['@/views/' + url + '.vue'], reslove)
        }
      }
      if (item && item.children.length > 0) {
        addComponent(item.children, item.ascription)
      }
    }
  })
  return routes
}

/**
 * 添加菜单
 * @param routes
 * @returns {*}
 */
function addMenus(routes, code) {
  const menu = routes
  menu.forEach(item => {
    item.name = item.path
    item.ascription = code || item.ascription
    item.name = item.componentName
    if (item.menuState === 1) {
      item.hidden = true
    }
    item.meta = {
      icon: item.icon,
      title: item.title,
      noCache: item.nocache === 1,
      ascription: code || item.ascription
    }
    if (item.children.length && item.ascription) {
      addMenus(item.children)
    }
  })
  return menu
}

export function copyTree(obj = {}) {
  return JSON.parse(JSON.stringify(obj))
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
